/********************************************************************************
 * Project Name		[JavaEE_Web]
 * File Name     	[CurrentOnlineNumberListener.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * 统计在线人数
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
@WebListener(value = "CurrentOnlineNumberListener")
public class CurrentOnlineNumberListener implements HttpSessionListener {

	/**
	 * 当Session创建时, 在线人数+1
	 * 
	 * @param se
	 */
	@Override
	public void sessionCreated(HttpSessionEvent se) {
		Integer currentOnlineNumber = calculateOnlineNumber(se, "create");
		System.out.println("当前在线人数:" + currentOnlineNumber);
	}

	/**
	 * 当Session销毁时, 在线人数-1
	 * 
	 * @param se
	 */
	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		Integer currentOnlineNumber = calculateOnlineNumber(se, "destroy");
		System.out.println("当前在线人数:" + currentOnlineNumber);
	}

	private Integer calculateOnlineNumber(HttpSessionEvent se, String event) {
		ServletContext servletContext = se.getSession().getServletContext();
		Integer currentOnlineNumber = (Integer) servletContext.getAttribute("currentOnlineNumber");
		if (currentOnlineNumber == null) {
			servletContext.setAttribute("currentOnlineNumber", 1);
			currentOnlineNumber = 1;
		} else {
			if ("create".equals(event)) {
				currentOnlineNumber++;
			}
			if ("destroy".equals(event)) {
				currentOnlineNumber--;
			}
			servletContext.setAttribute("currentOnlineNumber", currentOnlineNumber);
		}
		return currentOnlineNumber;
	}
}
